package com.vieewer.btdemo

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.lindroid.androidutilskt.extension.shortToast
import com.lindroid.androidutilskt.extension.systemBrightness
import com.vieewer.btdemo.view.brightness.SettingsActivity
import com.vieewer.btdemo.view.map.MapGuideActivity
import com.vieewer.classicbt.BleManager
import com.vieewer.classicbt.BluetoothPermissionHandler
import com.vieewer.classicbt.CLog
import com.vieewer.classicbt.Connect
import com.vieewer.classicbt.listener.*
import com.vieewer.classicbt.scan.ScanConfig
import kotlinx.android.synthetic.main.activity_main.*
import java.nio.ByteBuffer
import com.alibaba.fastjson.JSON
import com.vieewer.btdemo.bean.SystemSettingsBean.SYS_TYPE_BRIGHTNESS
import com.vieewer.btdemo.bean.SystemSettingsBean.SYS_TYPE_VOLUME
import com.lindroid.androidutilskt.statics.AppManager
import com.vieewer.btdemo.base.BaseActivity
import com.vieewer.btdemo.common.Constants.*
import com.vieewer.btdemo.view.microsoft.audio.TranslateAudioActivity
import com.vieewer.btdemo.view.microsoft.ocr.OcrActivity
import com.vieewer.btdemo.view.notification.DialogActivity
import com.vieewer.btdemo.view.wifi.TransferPhotosManager
import org.greenrobot.eventbus.EventBus
import android.widget.Toast
import com.jakewharton.rxbinding2.view.RxView
import com.tbruyelle.rxpermissions2.RxPermissions
import com.vieewer.btdemo.bean.*
import com.vieewer.btdemo.utils.CommunicateToGlassesHelper
import com.vieewer.btdemo.utils.CommunicateToPhoneHelper
import com.vieewer.btdemo.utils.LogUtil
import com.vieewer.btdemo.view.compass.CompassManager
import com.vieewer.btdemo.view.info.SugonGlassesInfoManager
import com.vieewer.btdemo.view.microsoft.qna.CreateKB
import com.vieewer.btdemo.view.microsoft.qna.GetAnswer
import com.vieewer.btdemo.view.mycamera.SurfaceCameraActivity
import com.vieewer.btdemo.view.wifi.connect.WifiConnectManager


class MainActivity : BaseActivity(), BluetoothPermissionCallBack {

    private lateinit var list: ArrayList<BluetoothDevice>
    var connect: Connect? = null
    private val permissionCallBack = BluetoothPermissionHandler(this, this)
    private var mAudioManager: AudioManager? = null
    //全局toast避免多次弹出
    private var mToast: Toast ? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
        initListeners()

    }


    override fun permissionFailed() {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        permissionCallBack.onActivityResult(requestCode, resultCode, data)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionCallBack.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onBlueToothEnabled() {

        BleManager.getInstance().init(application)
        BleManager.getInstance().setForegroundService(true)
        btn2.setOnClickListener {
            BleManager.getInstance().scan(ScanConfig(5000), object : ScanResultListener {
                override fun onDeviceFound(device: BluetoothDevice?) {
                    if (!isContained(device!!)) {
                        list.add(device)
                        recyclerview.adapter?.notifyDataSetChanged()

                    }
                }

                override fun onFinish() {
                }

                override fun onError() {
                }
            })
        }
        btn1.setOnClickListener {
            t("register server success.you can connnect device now.")
            registerServer()
        }

        btnDiscoverable.setOnClickListener {
            BleManager.getInstance().enableDiscoverable(300)
        }

        btn_send_data.setOnClickListener {
            write()
        }
    }


    fun registerServer() {
        BleManager.getInstance().registerServerConnection(object : ConnectResultlistner {
            override fun disconnected() {
                t("bluetooth has disconnected")
                BleManager.getInstance().destory()
                registerServer()
            }

            override fun connectSuccess(connect: Connect?) {
                this@MainActivity.connect = connect
                CommunicateToPhoneHelper.instance.connect = connect

                shortToast("server connect Success")
                read()
            }

            override fun connectFailed(e: Exception?) {

            }

        })
    }


    private fun initListeners() {
        settings.setOnClickListener{
            startActivity(Intent(this, SettingsActivity::class.java))
        }

        txt_test_map.setOnClickListener{
            startActivity(Intent(this, MapGuideActivity::class.java))
        }

        txt_test_sys.setOnClickListener{
            //startActivity(Intent(this, SugonGlassesInfoActivity::class.java))
            //TestNotificationActivity TestActivity CompassActivity OrientationActivity

/*            val i = Intent()
            i.component = ComponentName("com.vieewer.btdemo", "com.vieewer.btdemo.view.capture.CaptureService")
            i.action = CaptureService.ACTION_SINGLE_PIC
            mContext.startService(i)*/

            startActivity(Intent(this, SugonGlassesInfoManager::class.java))


        }

        txt_trans.setOnClickListener{
            startActivity(Intent(this, TranslateAudioActivity::class.java))
        }

        txt_trans_ocr.setOnClickListener{
            startActivity(Intent(this, OcrActivity::class.java))
        }

        txt_transfer_wifi.setOnClickListener {
            startActivity(Intent(this, TransferPhotosManager::class.java))
        }

        btn_connect_wifi.setOnClickListener {
            startActivity(Intent(this, WifiConnectManager::class.java))
        }


        btn_qna_create.setOnClickListener {
            startActivity(Intent(this, CreateKB::class.java))
        }


        btn_qna_get.setOnClickListener {
            startActivity(Intent(this, GetAnswer::class.java))
        }


        btn_qna_publish.setOnClickListener {
            //startActivity(Intent(this, PublishKB::class.java))

            /*val data = ChuanSceneBean()
            data.type = "sceneList"
            var dataList = ArrayList<ScenceBean>()
            for (i in 0..10) {
                var bean = ScenceBean()
                bean.audio = "http://audio2.kddaoyou.com/1457_0_hls.m3u8?auth_key=1574151868-0-0-23fe952756cc50404dbdbb1d65abd431"
                bean.city = "杭州"
                bean.description = "早先，苏东坡笔下，溪山处处皆可庐，最爱灵隐飞来孤，说的就是位于杭州的千年古刹灵隐寺，其背靠北高峰，面朝飞来峰，两峰挟峙，林木耸秀，实乃钟灵毓秀之地。开山祖师为西印度僧人慧理和尚，东晋咸和初，他由中原云游入浙，至武林，即今杭州，见有一峰而叹曰：“此乃中天竺国灵鹫山一小岭，不知何代飞来？佛在世日，多为仙灵所隐”，遂于峰前建寺，名曰灵隐，是中国佛教禅宗十大古刹之一。北周武帝年间，曾一度宣布废佛，并下令僧徒还俗，焚烧法器佛典，将寺庙充公，此次法难称为北周武帝灭佛，其对北方寺院打击很大，而南方寺院稍好些。不过有些胆小怕事的僧人，闻风法难之声，便悄悄溜走，真是树倒猢狲散，致使灵隐寺陷入冷落荒寂之中。灵隐寺的曲曲折折，绝不是几句话所能概括的，以后历朝历代都有不同程度的损毁和重修，好在苍天庇佑，才有今日香火鼎盛之景。"
                bean.key = "a1152632-f97d-11e6-a57a-00163e0005c0"
                bean.latitude = 30.2428299125216
                bean.longitude = 120.097163915634
                bean.pic = "http://site-res3.kddaoyou.com/zeus/site_photos/1457/000000_x.jpg-sitePic?auth_key=1574151868-0-0-b543731d3db6d8da9601b14a3168be3f"
                bean.title = "灵隐寺"
                dataList.add(bean)
            }

            data.scenceBeans = dataList
            val dataStr = JSON.toJSONString(data)
            LogUtil.e("yjj", "test 111 send data to sugon" + dataStr)
            CommunicateToGlassesHelper.instance.write(dataStr)*/

            var bean = WifiPhotoBean()
            bean.type = "photo"
            bean.btntype = "连接"
            bean.ip = ""
            val dataStr = JSON.toJSONString(bean)
            CommunicateToGlassesHelper.instance.write(dataStr)


        }


        btn_compass.setOnClickListener {
            startActivity(Intent(this, CompassManager::class.java))
        }


        setOnCameraClick()

    }



    private fun setOnCameraClick() {
        //拍照相关
        var rxPermissions = RxPermissions(this)
        RxView.clicks(txt_take_camera)
            .compose(
                rxPermissions.ensure(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            )
            .subscribe { granted ->
                if (granted!!) {
                    startVideoRecordActivity()
                } else {
                    Snackbar.make(txt_take_camera, getString(R.string.no_enough_permission), Snackbar.LENGTH_SHORT)
                        .setAction("Confirm", null).show()
                }
            }

    }


    private fun startVideoRecordActivity() {
        val intent = Intent(this, SurfaceCameraActivity::class.java)
        startActivityForResult(intent, 0)
    }


    private fun init() {
        TransferPhotosManager.getNewInstance().init(this@MainActivity)
        TransferPhotosManager.getNewInstance().register()

        mToast = Toast.makeText(this, "received message" , Toast.LENGTH_SHORT)
        mAudioManager = getSystemService(AUDIO_SERVICE) as AudioManager

        recyclerview.layoutManager = LinearLayoutManager(this)
        list = ArrayList()
        //recyclerview.adapter = MyAdapter(this, list)
        permissionCallBack.start()

        //t("register server success.you can connnect device now.")
        registerServer()
        //BleManager.getInstance().enableDiscoverable(300)
    }

    private fun isContained(result: BluetoothDevice): Boolean {
        if (result.name == null || "null".equals(result.name, ignoreCase = true))
            return true
        for (device in list) {
            if (result.address == device.address) {
                return true
            }
        }
        return false
    }

    fun read() {
//        val a:Int= -0x146f1470
//        val buffer=ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(a)
//        val b:Byte= 0x03
//        val buffer2=ByteBuffer.allocate(1).order(ByteOrder.LITTLE_ENDIAN).put(b)
   /*     connect?.setReadPacketVerifyListener(object : PacketDefineListener {
            override fun getPacketStart(): ByteArray {
                return start

            }

            override fun getPacketEnd(): ByteArray {
                return end

            }
        })*/
        connect?.read(object : TransferProgressListener {

            override fun transferSuccess(bytes: ByteArray?) {
                //t("received message")
                mToast!!.show()
                bytes?.let { it1 ->
                    tvReceive.text = String(it1)
                }

                operateResult(bytes)

            }

            override fun transferFailed(msg: Exception) {
                msg.printStackTrace()
//                msg.message?.run {
//                    t(this)
//                }

            }

            override fun transfering(progress: Int) {
                CLog.e("read progress:$progress")
            }
        })
    }


    private fun operateResult(bytes: ByteArray?) {

        var result = String(bytes!!)

        CLog.e("read string bytes ?>>>" + result)
        //todo try catch exception

        var jsonObject = JSON.parseObject(result)

        when (jsonObject["type"]) {

            COMMON_TYPE_STS_SETTING -> {

                var bean = JSON.parseObject(result, SystemSettingsBean::class.java)
                if (bean != null ) {
                    if (bean.sys_type == SYS_TYPE_BRIGHTNESS) {
                        systemBrightness = bean.progress
                    } else if (bean.sys_type == SYS_TYPE_VOLUME) {
                        mAudioManager!!.setStreamVolume(AudioManager.STREAM_MUSIC, bean.progress, AudioManager.FLAG_SHOW_UI)
                    }

                    CLog.e("system progress >>>" + bean.progress)
                }

            }

            COMMON_TYPE_MAP -> {
                var bean = JSON.parseObject(result, MapDataBean::class.java)
                if (bean != null ) {

                    if (AppManager.currentActivity()!!.localClassName == "view.map.MapGuideActivity") {
                        Log.i("yjj", "refresh map view" + AppManager.currentActivity()!!.localClassName)
                        MapGuideActivity.refreshView(bean)
                    } else {
                        Log.i("yjj", "goto map view")
                        var intent = Intent(AppManager.currentActivity(), MapGuideActivity::class.java)
                        intent.putExtra("data", bean)
                        startActivity(intent)
                    }

                }
            }

            COMMON_TYPE_NOTIFICATION -> {
                var bean = JSON.parseObject(result, NotificationBean::class.java)
                if (bean != null ) {
                    //判断手机屏幕是否亮着
                    var intent = Intent(AppManager.currentActivity(), DialogActivity::class.java)
                        intent.putExtra("data", bean)
                        startActivity(intent)
                }
            }

            COMMON_TYPE_TRANS_PHOTO -> {

                var bean = JSON.parseObject(result, WifiPhotoBean::class.java)
                if (bean != null ) {
                    TransferPhotosManager.getNewInstance().handleEvent(MessageEvent(bean.btntype, bean.ip))
                    //EventBus.getDefault().postSticky(MessageEvent(bean.btntype, bean.ip))
                }
            }

            COMMON_TYPE_CONNECT_WIFI -> {

                var bean = JSON.parseObject(result, WifiLinkBean::class.java)
                if (bean != null ) {
                    EventBus.getDefault().postSticky(bean)
                }

            }

            COMMON_TYPE_SWITCH -> {
                var bean = JSON.parseObject(result, SwitchBean::class.java)
                if (bean != null ) {
                    EventBus.getDefault().postSticky(bean)
                }

            }


            COMMON_TYPE_SCENE_DATA -> {
                var bean = JSON.parseObject(result, ChuanSceneBean::class.java)
                if (bean != null ) {
                    //EventBus.getDefault().postSticky(bean)
                    LogUtil.e("yjj", "receive from phone to get sceneList")
                }

            }



        }




    }

    private fun write() {
        val text = et.text.toString()
        val bytes = text.toByteArray()

        val b = ByteBuffer.allocate(bytes.size)
        b.put(bytes)


        connect?.write(b.array(), object : TransferProgressListener {
//            override fun disconnected() {
//                t("bluetooth has disconnected")
//
//            }

            override fun transferSuccess(bytes: ByteArray?) {
                t("send message successful")
            }

            override fun transferFailed(msg: Exception) {
                msg.message?.run {
                    t(this)
                }

            }

            override fun transfering(progress: Int) {
                CLog.e("write progress:$progress")
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        //BleManager.getInstance().destory()
        TransferPhotosManager.getNewInstance().unregisterAndStop()
    }








}
